package beautiful.butterfly.server.httpserver.handlers.notchange;

import beautiful.butterfly.server.application.Application;
import beautiful.butterfly.server.httpserver.handlers.HttpServer;
import beautiful.butterfly.server.httpserver.handlers.HttpServiceChannelInboundHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.codec.http.HttpObjectAggregator;
import io.netty.handler.codec.http.HttpRequestDecoder;
import io.netty.handler.codec.http.HttpResponseEncoder;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.stream.ChunkedWriteHandler;


public class HttpServiceChannelInitializer extends ChannelInitializer<SocketChannel> {

    private final SslContext sslContext;
    private final Application application;


    private HttpServer httpServer;

    public HttpServiceChannelInitializer(SslContext sslContext, Application application, HttpServer httpServer) {
        this.sslContext = sslContext;
        this.application = application;
        this.httpServer = httpServer;

    }

    @Override
    protected void initChannel(SocketChannel socketChannel) throws Exception {
        ChannelPipeline channelPipeline = socketChannel.pipeline();
        if (sslContext != null) {
            channelPipeline.addLast(sslContext.newHandler(socketChannel.alloc()));
        }

        // 服务端，对请求解码
        channelPipeline.addLast("http-decoder",
                new HttpRequestDecoder());
        // 聚合器，把多个消息转换为一个单一的FullHttpRequest或是FullHttpResponse
        channelPipeline.addLast("http-aggregator",
                new HttpObjectAggregator(65536));
        // 服务端，对响应编码
        channelPipeline.addLast("http-encoder",
                new HttpResponseEncoder());
        // 块写入处理器
        channelPipeline.addLast("http-chunked",
                new ChunkedWriteHandler());


        channelPipeline.addLast(new HttpServiceChannelInboundHandler(application, this.httpServer));
    }
}
